package com.bloveoacom.util;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.view.View;
import android.view.ViewGroup;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

public class PicCameraLocalUtil {
    public static final String IMAGE_UNSPECIFIED = "image/*";

    /**
     * 选择文件
     */
    public static void selectFileFromLocal(Context context) {
        Intent intent = null;
        if (Build.VERSION.SDK_INT < 19) {
            intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("*/*");
            intent.addCategory(Intent.CATEGORY_OPENABLE);
        } else {
            intent = new Intent(
                    Intent.ACTION_PICK,
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        }
        ((Activity) context).startActivityForResult(intent, Constant.REQUEST_CODE_SELECT_FILE);
    }

    /**
     * 发�?文件
     *
     * @param uri
     */
    public static File getFile(Context context, Uri uri) {
        String filePath = null;
        if ("content".equalsIgnoreCase(uri.getScheme())) {
            String[] projection = {"_data"};
            Cursor cursor = null;
            try {
                cursor = context.getContentResolver().query(uri, projection, null, null, null);
                int column_index = cursor.getColumnIndexOrThrow("_data");
                if (cursor.moveToFirst()) {
                    filePath = cursor.getString(column_index);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            filePath = uri.getPath();
        }
        File file = new File(filePath);
        if (file == null || !file.exists()) {
            ToastUtil.makeShortText(context, "文件不存");
            return null;
        }
        if (file.length() > 10 * 1024 * 1024) {
            ToastUtil.makeShortText(context, "文件太大");
            return null;
        }
        return file;

    }

    /**
     * 根据图库图片uri发�?图片
     *
     * @param selectedImage
     */
    public static String getPicByUri(Context context, Uri selectedImage) {
        // String[] filePathColumn = { MediaStore.Images.Media.DATA };
        String path = "";
        Cursor cursor = context.getContentResolver().query(selectedImage, null,
                null, null, null);
        if (cursor != null) {
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex("_data");
            String picturePath = cursor.getString(columnIndex);
            cursor.close();
            cursor = null;
            if (picturePath == null || picturePath.equals("null")) {
                ToastUtil.makeShortText(context, "没有找到照片");
                picturePath = "";
            }
            path = picturePath;
        } else {
            File file = new File(selectedImage.getPath());
            if (!file.exists()) {
                ToastUtil.makeShortText(context, "没有找到照片");
            }
            path = file.getAbsolutePath();
        }
        return path;

    }

    /**
     * 从图库获取图片
     */
    public static void selectPicFromLocal(Fragment f) {
        Intent intent;
        if (Build.VERSION.SDK_INT < 19) {
            intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");
        } else {
            intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        }
        f.startActivityForResult(intent, Constant.REQUEST_CODE_LOCAL);
    }



    /**
     * 从图库获取图片
     */
    public static void selectPicFromLocal(Activity activity) {
        Intent intent;
        if (Build.VERSION.SDK_INT < 19) {
            intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");
        } else {
            intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        }
        activity.startActivityForResult(intent, Constant.REQUEST_CODE_LOCAL);
    }

    /**
     * 系统页面来裁剪传进来的照片
     *
     */
    public static void startPhotoZoom(Uri uri, Fragment fragment) {
        // 裁剪图片意图
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, IMAGE_UNSPECIFIED);
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽�?
        intent.putExtra("outputX", 64);
        intent.putExtra("outputY", 64);
        intent.putExtra("return-data", true);
        fragment.startActivityForResult(intent, Constant.PHOTORESOULT);
    }

    /**
     * 压缩图片
     *
     * @param path
     * @param context
     * @return
     * @throws IOException
     */
    public static File revitionImageSize(String path, Context context)
            throws IOException {
        BufferedInputStream in = new BufferedInputStream(new FileInputStream(new File(path)));
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(in, null, options);
        in.close();
        int i = 0;
        Bitmap bitmap = null;
        while (true) {
            if ((options.outWidth >> i <= 1080) && (options.outHeight >> i <= 1920)) {
                in = new BufferedInputStream(new FileInputStream(new File(path)));
                options.inSampleSize = (int) Math.pow(2.0D, i);
                options.inJustDecodeBounds = false;
                bitmap = BitmapFactory.decodeStream(in, null, options);
                break;
            }
            i += 1;
        }
        return saveBitmap(context, bitmap);
    }

    /**
     * 保存图片到指定目录
     *
     * @param mBitmap
     */
    public static File saveBitmap(Context context, Bitmap mBitmap) {
        Date mDate = new Date();
        String imgName = Long.toString(mDate.getTime()) + ".jpg";
        File mFile = new File(AppUtil.getAppDir(context) + "/image/");
        if (!mFile.exists()) {
            mFile.mkdirs();
        }
        try {
            FileOutputStream out = new FileOutputStream(mFile.getAbsolutePath() + "/" + imgName);
            mBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        mFile = new File(mFile.getAbsolutePath() + "/" + imgName);
        return mFile;
    }

    /**
     * 保存图片到指定目录
     *
     * @param mBitmap
     */
    public static File saveBitmap(Context context, Bitmap mBitmap, String name) {
        // File mFile = new File(Environment.getRootDirectory()+"/oAimages");
        String imgName = name + ".jpg";
        File mFile = new File(AppUtil.getAppDir(context) + "/image/");
        if (!mFile.exists()) {
            mFile.mkdirs();
        }
        try {
            FileOutputStream out = new FileOutputStream(mFile.getAbsolutePath()
                    + "/" + imgName);
            mBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new File(mFile.getAbsolutePath() + "/" + imgName);

    }
    public static File showPic(Context mContext, View layout_share) {
//        int width = layout_share.getMeasuredWidth();
//        int height = layout_share.getMeasuredHeight();
        int[] ints = measureView(layout_share);
        Bitmap b = Bitmap.createBitmap(ints[0], ints[1], Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(b);
        layout_share.draw(canvas);
        return PicCameraLocalUtil.saveBitmap(mContext, b,"share_webview");
    }

    public static File showPic2(Context mContext, View layout_share) {
        int width = layout_share.getMeasuredWidth();
        int height = layout_share.getMeasuredHeight();
        Bitmap b = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(b);
        layout_share.draw(canvas);
        return PicCameraLocalUtil.saveBitmap(mContext, b,"share2_webview");
    }

    public static int[] unDisplayViewSize(View view) {
        int size[] = new int[2];
        int width = View.MeasureSpec.makeMeasureSpec(0,
                View.MeasureSpec.UNSPECIFIED);
        int height = View.MeasureSpec.makeMeasureSpec(0,
                View.MeasureSpec.UNSPECIFIED);
        view.measure(width, height);
        size[0] = view.getMeasuredWidth();
        size[1] = view.getMeasuredHeight();
        return size;
    }

    public static int[] measureView(final View view) {
        ViewGroup.LayoutParams lp = view.getLayoutParams();
        if (lp == null) {
            lp = new ViewGroup.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT
            );
        }
        int widthSpec = ViewGroup.getChildMeasureSpec(0, 0, DisplayUtil.getDensityWdith(view.getContext()));
        int lpHeight = lp.height;
        int heightSpec;
        if (lpHeight > 0) {
            heightSpec = View.MeasureSpec.makeMeasureSpec(lpHeight, View.MeasureSpec.EXACTLY);
        } else {
            heightSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        }
        view.measure(widthSpec, heightSpec);
        return new int[]{view.getMeasuredWidth(), view.getMeasuredHeight()};
    }


    public static Bitmap getBitmap(View layout_share){
        int width =     layout_share.getMeasuredWidth();
        int height = layout_share.getMeasuredHeight();
        Bitmap b = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(b);
        layout_share.draw(canvas);
        return b;
    }

    public static Bitmap getBitmapFromDrable(Context mContext, int resd){
        return BitmapFactory.decodeResource(mContext.getResources(), resd);
    }



    public static Bitmap hc(Bitmap head, Bitmap content, Bitmap header){
        if (head == null) {
            return null;
        }
        int headWidth = head.getWidth();
        int contentwidth = content.getWidth();
        int footerwidth = header.getWidth();

        int headHeight = head.getHeight();
        int kebiaoheight = content.getHeight();
        int footerheight = header.getHeight();
        //生成三个图片合并大小的Bitmap
        Bitmap newbmp = Bitmap.createBitmap(contentwidth, headHeight + kebiaoheight + footerheight, Bitmap.Config.ARGB_8888);
        Canvas cv = new Canvas(newbmp);
        cv.drawBitmap(head, 0, 0, null);// 在 0，0坐标开始画入headBitmap

        //因为手机不同图片的大小的可能小了 就绘制白色的界面填充剩下的界面
        if (headWidth < contentwidth) {
            System.out.println("绘制头");
            Bitmap ne = Bitmap.createBitmap(contentwidth - headWidth, headHeight, Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(ne);
            canvas.drawColor(Color.WHITE);
            cv.drawBitmap(ne, headWidth, 0, null);
        }
        cv.drawBitmap(content, 0, headHeight, null);// 在 0，headHeight坐标开始填充课表的Bitmap
        cv.drawBitmap(header, 0, headHeight + kebiaoheight, null);// 在 0，headHeight + kebiaoheight坐标开始填充课表的Bitmap
        //因为手机不同图片的大小的可能小了 就绘制白色的界面填充剩下的界面
        if (footerwidth < contentwidth) {
            System.out.println("绘制");
            Bitmap ne = Bitmap.createBitmap(contentwidth - footerwidth, footerheight, Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(ne);
            canvas.drawColor(Color.WHITE);
            cv.drawBitmap(ne, footerwidth, headHeight + kebiaoheight, null);
        }
        cv.save(Canvas.ALL_SAVE_FLAG);// 保存
        cv.restore();// 存储
        //回收
//        head.recycle();
//        content.recycle();
//        header.recycle();
        return newbmp;
    }


    public static void recycle(Bitmap ne){
        if(ne!=null&&!ne.isRecycled()){
            ne.recycle();
        }
    }



}
